const UserService = require("../services/UserService")
const JWT = require("../util/JWT")
const UserController = {
    addUser: async (req, res) => {
        console.log(req.body, req.file)
        //插入数据库
        //1 创建一个模型(user,限制filed类型),  一一对应数据库的集合
        //user.create添加数据     user.find查询数据     user.delete删除数据      user.update更新数据
        const avatar =req.file? `/uploads/${req.file.filename}` : '/images/touxiang.svg'
        const { username, password, age } = req.body
        await UserService.addUser(username, password, age,avatar)
        res.send({
            ok: 1
        })
        
    },
    updateUser: async (req,res) =>{
        console.log(req.body,req.params)
        const { username, password, age } = req.body
        await UserService.updateUser(username, password, age, req)
        res.send({
            ok: 1
        })
    },
    deleteUser: async (req,res) =>{
        console.log(req.params)
        await UserService.deleteUser(req.params.id)
        res.send({
            ok: 1
        })
    },
    findUser: async (req,res) =>{
        console.log( 111111,req.query)
        const { page, limit } = req.query
        const data = await UserService.findUser(page, limit)
        
        res.send({
            data,
            ok: 1
        })
    },
    login: async (req,res) =>{
        console.log(req.body)
        const { username, password } = req.body
        const data = await UserService.login(username, password)
        if(data.length === 0){
            res.send({
                ok: 0,
            })
        }else{
            // 设置session
            //只要没登录就不会有这个属性
            //req.session.user = data[0]   //设置session对象,默认存在内存中

            //设置session不安全,所以设置token
            const token = JWT.generate({
                _id: data[0]._id,
                username: data[0].username
            }, '1h')
            //token返回在header中
            res.header('Authorization',token)
            res.send({
                ok: 1,
                data
            })
        }
    },
    logout: (req,res) =>{
        // 销毁session
        req.session.destroy()
        res.send({
            ok: 1
        })
    }
    
}

module.exports = UserController